/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class DateHeaderParser extends HeaderParserBase<DateHeaderImpl> {
    private static final Log logger = LogFactory.getLog(DateHeaderParser.class);

    private DateFormat df = new SimpleDateFormat("EEE',' dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);

    protected Log getLogger() {
        return logger;
    }

    public DateHeaderImpl createLazily(byte[] data, int start, int end) {
        return new DateHeaderImpl(data, start, end);
    }

    public DateHeaderImpl[] parse(DateHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new DateHeaderImpl();
        final int startOfData = ByteArrayUtil.firstMissing(data, ' ', start, end);
        int endOfData = ByteArrayUtil.lastMissing(data, ' ', startOfData, end);
        if (endOfData == -1)
            throw new ParseException("Cannot parse the Date header!", startOfData);
        else
            endOfData++;
        final Calendar cal = GregorianCalendar.getInstance(Locale.US);
        cal.setTime(parseDate(new String(data, startOfData, endOfData - startOfData)));
        header.setDate(cal);
        return new DateHeaderImpl[]{header};
    }

    synchronized Date parseDate(String dateStr) throws ParseException {
        return df.parse(dateStr);
    }

    synchronized String formatDate(Date date) {
        return df.format(date);
    }
}
/*
 * $Log$
 */